package com.king.armips.android.dialog;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.ValueCallback;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.king.armips.android.MainActivity;
import com.king.armips.android.R;
import com.king.armips.android.utils.FileUtils;
import com.king.armips.android.utils.ScreenUtils;
import com.king.armips.android.utils.SoftKeyBoardUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SidebarDialog extends Dialog {
    private MainActivity mActivity;

    private RecyclerView rvFiles;
    private FileAdapter fileAdapter;
    private List<String> preFileNameList = new ArrayList<>();

    private EditText etRename;

    private FileOptionsPop fileOptionsPop;

    private AlertDialog renameDialog;
    private boolean isRename = true;

    private OnItemClickListener onItemClickListener;

    private File baseDir;

    private int selectedIndex = -1;

    public SidebarDialog(@NonNull MainActivity context) {
        super(context, R.style.AppDialog);
        mActivity = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_sidebar);
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = (int) (ScreenUtils.screenWidth *0.8f);
        layoutParams.height = ScreenUtils.screenHeight;
        layoutParams.gravity = Gravity.START | Gravity.TOP;
        window.setWindowAnimations(R.style.SidebarDialogAnim);
        window.setAttributes(layoutParams);

        rvFiles = findViewById(R.id.rv_files);

        fileAdapter = new FileAdapter(preFileNameList);
        rvFiles.setLayoutManager(new LinearLayoutManager(getContext()));
        rvFiles.setAdapter(fileAdapter);

        fileAdapter.onItemClickListener = (parent, view, position, id) -> {
            selectedIndex = position;
            if (id == 0){
                //选择文件
                dismiss();
                if (onItemClickListener != null){
                    onItemClickListener.onSelected(fileAdapter.getItem(position));
                }
            }
            else {
                //更多选项
                showFileOptionsPop(view);
            }
        };

        findViewById(R.id.tv_import).setOnClickListener(v -> {
            rvFiles.postDelayed(this::dismiss,400);
            if (onItemClickListener != null){
                onItemClickListener.importFile();
            }
        });

        findViewById(R.id.btn_create_file).setOnClickListener(v -> {
            showRenameDialog("",false);
        });

        findViewById(R.id.btn_close).setOnClickListener(v -> dismiss());

    }

    public void setBaseDir(File baseDir) {
        this.baseDir = baseDir;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void refreshFiles(){
        ArrayList<String> fileNameList = new ArrayList<>();
        scanFile(baseDir,baseDir.getAbsolutePath()+"/",fileNameList);

        Collections.sort(fileNameList);

        if (rvFiles == null){
            preFileNameList = fileNameList;
        }
        else {
            rvFiles.post(()-> fileAdapter.updateFileList(fileNameList));
        }
    }

    private void scanFile(File dir,String basePath,List<String> fileNameList){
        File[] files = dir.listFiles();
        if (files == null)
            return;
        if (files.length == 0){
            //删除空目录
            FileUtils.delete(dir);
            return;
        }
        for (File file : files){
            if (file.isDirectory()){
                scanFile(file,basePath,fileNameList);
            }
            else {
                fileNameList.add(file.getAbsolutePath().substring(basePath.length()));
            }
        }
    }

    private void showFileOptionsPop(View anchorView){
        if (fileOptionsPop == null){
            fileOptionsPop = new FileOptionsPop(mActivity);

            fileOptionsPop.setOnItemClickListener((parent, view, position, id) -> {
                String name = fileAdapter.getItem(selectedIndex);
                File file = new File(baseDir, name);
                switch (position){
                    case 0://重命名
                        showRenameDialog(name,true);
                        break;
                    case 1://导出
                        FileUtils.saveAs(mActivity.getLauncher(),file,result -> {
                            Intent data = result.getData();
                            boolean hasUri = false;
                            if (data != null){
                                Uri uri = data.getData();
                                if (uri != null){
                                    hasUri = true;
                                }
                            }

                            if (hasUri){

                                if (onItemClickListener != null){
                                    onItemClickListener.onExported(name);
                                }

                                Toast.makeText(mActivity,R.string.file_export_success,Toast.LENGTH_SHORT).show();

                            }
                            else {
                                Toast.makeText(mActivity,R.string.file_export_failed,Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;
                    case 2: //删除
                        FileUtils.delete(file);
                        fileAdapter.removeAt(selectedIndex);

                        if (onItemClickListener != null){
                            onItemClickListener.onDeleted(name);
                        }

                        Toast.makeText(mActivity,mActivity.getString(R.string.file_deleted_of,name),Toast.LENGTH_SHORT).show();
                        break;
                }
                rvFiles.postDelayed(()-> fileOptionsPop.dismiss(),150);
            });

        }
        fileOptionsPop.showAsDropDown(anchorView,0,-ScreenUtils.dp2px(mActivity,10),Gravity.START);
    }

    public void showRenameDialog(String name,boolean isRename){
        this.isRename = isRename;
        if (renameDialog == null){
            renameDialog = new AlertDialog.Builder(mActivity)
//                    .setTitle(R.string.rename)
                    .setView(R.layout.dialog_edittext)
                    .setNegativeButton(R.string.cancel, (dialog, which) -> { })
                    .setPositiveButton(R.string.ok, null)
                    .create();
            renameDialog.setCanceledOnTouchOutside(false);
            Window window = renameDialog.getWindow();
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = (int) (ScreenUtils.screenWidth *0.75f);
            window.setAttributes(layoutParams);
        }
        renameDialog.setTitle(isRename ? R.string.rename : R.string.create_file);
        renameDialog.show();
        if (etRename == null){
            etRename = renameDialog.findViewById(R.id.edittext);
            etRename.setImeOptions(EditorInfo.IME_ACTION_DONE);
            etRename.setSingleLine();
            etRename.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE){
                    if (!doRename())
                        return false;

                    renameDialog.dismiss();
                    return true;
                }
                return false;
            });
            renameDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
                if (doRename()){
                    renameDialog.dismiss();
                }
            });
        }
        etRename.setText(name);
        etRename.setSelection(name.length());
        etRename.postDelayed(()-> SoftKeyBoardUtils.showSoftKeyboard(etRename),150);
    }

    private boolean doRename(){
        String newName = etRename.getText().toString().trim();
        if (TextUtils.isEmpty(newName)){
            Toast.makeText(mActivity,R.string.file_name_cannot_empty,Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!FileUtils.verifyFilename(baseDir, newName)){
            Toast.makeText(mActivity,R.string.file_name_invalid,Toast.LENGTH_SHORT).show();
            return false;
        }

        File newFile = new File(baseDir,newName);

        if (newFile.exists()){
            Toast.makeText(mActivity,isRename ? R.string.file_name_exists : R.string.file_exists,Toast.LENGTH_SHORT).show();
            return false;
        }

        if (isRename){
            // 重命名
            File srcFile = new File(baseDir,fileAdapter.getItem(selectedIndex));

            if (srcFile.renameTo(newFile)){

                fileAdapter.updateItem(selectedIndex,newName);

                if (onItemClickListener != null){
                    onItemClickListener.onRenamed(newFile.getName());
                }

                Toast.makeText(mActivity,R.string.file_renamed_success,Toast.LENGTH_SHORT).show();
                return true;
            }

            Toast.makeText(mActivity,R.string.file_renamed_failed,Toast.LENGTH_SHORT).show();
        }
        else {
            // 新建文件
            try {
                if (newFile.createNewFile()){
                    refreshFiles();
                    Toast.makeText(mActivity,R.string.file_created_success,Toast.LENGTH_SHORT).show();
                    return true;
                }
            } catch (Exception e){
                e.printStackTrace();
            }

            Toast.makeText(mActivity,R.string.file_created_failed,Toast.LENGTH_SHORT).show();
        }

        return true;
    }

    private static class ViewHolder extends RecyclerView.ViewHolder{
        TextView tvName;
        View btnMore;

        public ViewHolder(@NonNull ViewGroup parent) {
            super(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_file, parent, false));
            tvName = itemView.findViewById(R.id.tv_name);
            btnMore = itemView.findViewById(R.id.btn_more);

        }
    }

    private static class FileAdapter extends RecyclerView.Adapter<ViewHolder> {
        private final List<String> mList = new ArrayList<>();
        private AdapterView.OnItemClickListener onItemClickListener;

        public FileAdapter(List<String> fileList) {
            if (fileList != null && !fileList.isEmpty()){
                mList.addAll(fileList);
            }
        }

        @SuppressLint("NotifyDataSetChanged")
        private void updateFileList(List<String> list){
            mList.clear();
            if (list != null) {
                mList.addAll(list);
            }
            notifyDataSetChanged();
        }

        public void removeAt(int position){
            int lastSize = mList.size();
            mList.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position,lastSize - position);
        }

        public void updateItem(int position,String name){
            mList.set(position,name);
            notifyItemChanged(position);
        }

        public String getItem(int position){
            return mList.get(position);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder(parent);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            String filename = mList.get(position);
            holder.tvName.setText(filename);

            holder.tvName.setOnClickListener(v -> {
                if (onItemClickListener != null){
                    onItemClickListener.onItemClick(null,v,position,0);
                }
            });

            holder.btnMore.setOnClickListener(v -> {
                if (onItemClickListener != null){
                    onItemClickListener.onItemClick(null,v,position,1);
                }
            });

        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

    }

    public interface OnItemClickListener {
        void importFile();

        void onSelected(String filePath);
        void onRenamed(String name);
        void onDeleted(String filePath);

        default void onExported(String filePath){}
    }

}
